package bysj.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebFilter(filterName = "Filter 0",urlPatterns = {"/*"})
public class Filter0_encoding implements Filter {
    public void destroy(){}
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException{
        System.out.println("Filter 0 - encoding begins");
        HttpServletRequest request = (HttpServletRequest)req;
        HttpServletResponse response = (HttpServletResponse)res;
        //获得path
        String path = request.getRequestURI();
        System.out.println(path);
        //如果没有字串“/login”，则考虑设置字符编码
        if(!path.contains("/login")){
            //所有的资源都要设置响应字符集
            //response.setContentType("text/html,charset=UTF8");
            request.setCharacterEncoding("UTF-8");
            response.setContentType("application/json;charset=UTF-8");

            String method = request.getMethod();
            if("DELETE".contains(method)){
                response.setContentType("application/json;charset=UTF-8");
            }
        }
        chain.doFilter(req,res);
        System.out.println("Filter 0 - encoding ends");
    }
    public void init(FilterConfig config) throws ServletException{}
}
